//
//  YFDatePicker.m
//  DatePickerDemo
//
//  Created by Winny Zhang on 2019/4/4.
//  Copyright © 2019 Winny Zhang. All rights reserved.
//

#import "YFDatePicker.h"
#import "NSDate+YFExtension.h"

@interface YFDatePicker () <UIPickerViewDataSource, UIPickerViewDelegate>

/**
 年份 PickerView
 */
@property (weak, nonatomic) IBOutlet UIPickerView *yearPicker;

/**
 月份 PickerView
 */
@property (weak, nonatomic) IBOutlet UIPickerView *monthPicker;

/**
 日 PickerView
 */
@property (weak, nonatomic) IBOutlet UIPickerView *dayPicker;

/**
 年份 数组
 */
@property (nonatomic, strong) NSArray <NSString *> *years;

/**
 月份 数组
 */
@property (nonatomic, strong) NSArray <NSString *> *months;

/**
 日 数组
 */
@property (nonatomic, strong) NSArray <NSString *> *days;

/**
 选中的年份 默认当前时间的年份
 */
@property (nonatomic,assign) NSInteger selectedYear;

/**
 选中的月份 默认当前时间的月份
 */
@property (nonatomic, assign) NSInteger selectedMonth;

/**
 选中的日 默认当前时间的日
 */
@property (nonatomic, assign) NSInteger selectedDay;

@end

@implementation YFDatePicker

/**
 初始化

 @param frame frame
 @return datePicker
 */
+ (instancetype)datePickerWithFrame:(CGRect)frame {
    YFDatePicker *picker = [[NSBundle mainBundle] loadNibNamed:@"YFDatePicker" owner:nil options:nil].firstObject;
    picker.frame = frame;
    return picker;
}

/**
 init方法初始化

 @param frame frame
 @return datePicker
 */
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self = [[NSBundle mainBundle] loadNibNamed:@"YFDatePicker" owner:nil options:nil].firstObject;
        [self setupViews];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self setupViews];
    }
    return  self;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    [self setupViews];
}

- (void)setupViews {
    
    self.yearPicker.dataSource = self;
    self.yearPicker.delegate = self;
    self.monthPicker.dataSource = self;
    self.monthPicker.delegate = self;
    self.dayPicker.dataSource = self;
    self.dayPicker.delegate = self;
    
    self.selectedYear = [NSDate date].currentYear;
    self.selectedMonth = [NSDate date].currentMonth;
    self.selectedDay = [NSDate date].currentDay;
    
    [self.yearPicker reloadAllComponents];
    [self.monthPicker reloadAllComponents];
    [self.dayPicker reloadAllComponents];
    
    NSString *selectyearString = [NSString stringWithFormat:@"%zd", self.selectedYear];
    [self.yearPicker selectRow: [self indexInArray:self.years value:selectyearString] inComponent:0 animated:YES];
    
    NSString *selectedMonthString = [NSString stringWithFormat:@"%zd", self.selectedMonth];
    [self.monthPicker selectRow:[self indexInArray:self.months value:selectedMonthString] inComponent:0 animated:YES];
    
    NSString *selectedDayString = [NSString stringWithFormat:@"%zd", self.selectedDay];
    [self.dayPicker selectRow:[self indexInArray:self.days value:selectedDayString] inComponent:0 animated:YES];
}

#pragma mark - UIPickerViewDataSource, UIPickerViewDelegate
- (NSInteger)numberOfComponentsInPickerView:(nonnull UIPickerView *)pickerView {
    return 1;
}

- (NSInteger)pickerView:(nonnull UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    
    switch (pickerView.tag) {
        case 365:
            return self.years.count;
            break;
        case 12:
            return self.months.count;
            break;
        case 30:
            return self.days.count;
            break;
        default:
            return 0;
            break;
    }
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(nullable UIView *)view {
    
    UIColor *lineColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:1];
    
    // 隐藏横线
    ((UIView *)[pickerView.subviews objectAtIndex:1]).backgroundColor = lineColor;
    ((UIView *)[pickerView.subviews objectAtIndex:2]).backgroundColor = lineColor;
    
    // 显示内容
    UILabel *label = [[UILabel alloc] init];
    label.frame = CGRectMake(0, 0, pickerView.frame.size.width, 35);
    label.textColor = [UIColor blackColor];
    label.textAlignment = NSTextAlignmentCenter;
    
    // 赋值
    switch (pickerView.tag) {
        case 365:
            label.text = self.years[row];
            break;
        case 12:
            label.text = self.months[row];
            break;
        case 30:
            label.text = self.days[row];
            break;
        default:
            break;
    }
    return label;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component {
    return 35;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    
    switch (pickerView.tag) {
        case 365:
            self.selectedYear = self.years[row].integerValue;
            break;
        case 12:
            self.selectedMonth = self.months[row].integerValue;
            break;
        case 30:
            self.selectedDay = self.days[row].integerValue;
            break;
        default:
            break;
    }
    if (_selectedDateCompletion) {
        
        NSString *yearString = [NSString stringWithFormat:@"%zd", self.selectedYear];
        NSString *monthString = [NSString stringWithFormat:@"%zd", self.selectedMonth];
        NSString *dayString = [NSString stringWithFormat:@"%zd", self.selectedDay];
        
        _selectedDateCompletion(yearString, monthString, dayString);
    }
}




#pragma mark - lazy load
- (NSArray <NSString *> *)years {
    if (!_years) {
        NSInteger minyear = 1970;
        NSInteger maxYear = [NSDate date].currentYear + 50;
        NSInteger length = maxYear - minyear;
        NSMutableArray *years = [NSMutableArray arrayWithCapacity:length];
        for (int i = 0; i < length; i++) {
            [years addObject:[NSString stringWithFormat:@"%zd", minyear]];
            minyear += 1;
        }
        _years = years;
    }
    return _years;
}

- (NSArray <NSString *> *)months {
    if (!_months) {
        NSInteger month = 1;
        NSMutableArray *months = [NSMutableArray arrayWithCapacity:12];
        for (int j = 0; j< 12; j++) {
            [months addObject:[NSString stringWithFormat:@"%zd", month]];
            month += 1;
        }
        _months = months;
    }
    return _months;
}

- (NSArray <NSString *> *)days {
    NSInteger length = [NSDate daysWithYear:self.selectedYear month:self.selectedMonth];
    NSMutableArray *days = [NSMutableArray arrayWithCapacity:length];
    NSInteger day = 1;
    for (int i = 0; i < length; i++) {
        [days addObject:[NSString stringWithFormat:@"%zd", day]];
        day += 1;
    }
    _days = days;
    return _days;
}


#pragma mark - 获取元素在数组中的位置
- (NSInteger)indexInArray:(NSArray <NSString *> *)array value:(NSString *)value {
    __block NSInteger index = 0;
    [array enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (value.integerValue == obj.integerValue) {
            index = idx;
        }
    }];
    return index;
}


#pragma mark - Setter
- (void)setMinimumYear:(NSInteger)minimumYear {
    
    if (minimumYear > 0) {
        
        _minimumYear = minimumYear;
        NSInteger length = 50;
        
        if (_maximumYear > 0 && _maximumYear > minimumYear) {
            
            length = _maximumYear - minimumYear + 1;
        }
        
        NSInteger year = minimumYear;
        NSMutableArray *years = [NSMutableArray arrayWithCapacity:length];
        
        for (int i = 0; i < length; i++) {
            
            [years addObject:[NSString stringWithFormat:@"%zd", year]];
            year += 1;
        }
        self.years = years;
        [self.yearPicker reloadAllComponents];
    }
}

- (void)setMaximumYear:(NSInteger)maximumYear {
    
    if (maximumYear > 0) {
        
        _maximumYear = maximumYear;
        NSInteger length = 0;
        NSInteger minYear = 1970;
        
        if (_minimumYear > 0 && _minimumYear < maximumYear) {
            
            length = maximumYear - _minimumYear + 1;
            minYear = _minimumYear;
            
        } else if (maximumYear <= minYear) {
            
            length = 0;
            
        } else {
            
            length = maximumYear - minYear + 1;
        }
        NSMutableArray *years = [NSMutableArray arrayWithCapacity:length];
        
        for (int i = 0; i < length; i++) {
            
            [years addObject:[NSString stringWithFormat:@"%zd", minYear]];
            minYear += 1;
        }
        self.years = years;
        [self.yearPicker reloadAllComponents];
    }
}





@end
